<template>
  <view class="store-detail-container">
    <!-- 头部信息部分 -->
    <view class="store-header">
      <view class="store-logo">
        <image :src="storeInfo.imgUrl"></image>
      </view>
      <view class="store-basic-info">
        <text class="store-name">{{ storeInfo.name }}</text>
        <view class="store-meta">
          <text>月售: {{ storeInfo.sales }}</text>
          <text>起送: {{ storeInfo.expressLimit }}</text>
          <text>基础运费: {{ storeInfo.expressPrice }}</text>
        </view>
        <text class="store-slogan">{{ storeInfo.slogan }}</text>
      </view>
    </view>

    <!-- 主体内容部分，包含左侧按钮和右侧商品数据 -->
    <view class="main-content">
      <!-- 左侧按钮栏 -->
      <view class="button-column">
        <view 
          class="button-item" 
          :class="{ active: activeTab === 'all' }"
          @click="showAllProducts"
        >
          全部商品
        </view>
        <view 
          class="button-item" 
          :class="{ active: activeTab === 'seckill' }"
          @click="showSeckillProducts"
        >
          秒杀
        </view>
        <view 
          class="button-item" 
          :class="{ active: activeTab === 'fruit' }"
          @click="showFreshFruitProducts"
        >
          新鲜水果
        </view>
      </view>

      <!-- 右侧商品列表部分 -->
      <view class="product-list">
        <view class="product-item" v-for="(product, index) in currentProductList" :key="index">
          <view class="product-img">
            <image :src="product.imgUrl"></image>
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <text class="product-sales">月售 {{ product.sales }} 件</text>
            <text class="product-price">
              <text class="price-current">¥{{ product.price }}</text>
              <text class="price-old">¥{{ product.oldPrice }}</text>
            </text>
          </view>
          <view class="quantity-control">
            <view class="minus" @click="decreaseQuantity(product)">-</view>
            <view class="quantity-num">{{ getProductQuantity(product) }}</view>
            <view class="plus" @click="addToCart(product)">+</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="bottom-nav">
      <view class="cart-icon" @click="toggleCartPopup">
        <view class="cart-badge">{{ getCurrentStoreCartQuantity() }}</view>
        <image src="/static/basket.png" mode="aspectFit"></image>
      </view>
      <view class="total-price">¥{{ currentStoreSelectedTotalPrice }}</view>
      <view v-if="hasItemsInCurrentStoreCart" class="checkout-btn" @click="checkout">去结算</view>
    </view>

    <!-- 购物车弹窗（只显示当前店铺的商品） -->
    <view v-if="isCartPopupVisible" class="cart-popup">
      <view class="cart-header">
        <view class="select-all">
          <checkbox :checked="isCurrentStoreAllSelected" @click="toggleCurrentStoreAllSelection"/> 全选
        </view>
        <view class="clear-cart" @click="clearCurrentStoreCart">清空购物车</view>
      </view>

      <view v-for="(item, itemIndex) in currentStoreCart" :key="itemIndex">
        <view class="product-item-popup">
          <view class="product-select">
            <checkbox :checked="item.selected" @click="toggleProductSelection(item)"/>
          </view>
          <view class="product-img-popup">
            <image :src="item.imgUrl"></image>
          </view>
          <view class="product-info-popup">
            <text class="product-name-popup">{{ item.name }}</text>
            <text class="product-sales-popup">月售 {{ item.sales }} 件</text>
            <text class="product-price-popup">
              <text class="price-current-popup">¥{{ item.price }}</text>
              <text class="price-old-popup">¥{{ item.oldPrice }}</text>
            </text>
          </view>
          <view class="quantity-control-popup">
            <view class="minus" @click="changeCartItemQuantity(item, -1)">-</view>
            <view class="quantity-num">{{ item.quantity }}</view>
            <view class="plus" @click="changeCartItemQuantity(item, 1)">+</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config.js';

export default {
  data() {
    return {
      storeInfo: {},
      allProducts: [],
      seckillProducts: [],
      freshFruitProducts: [],
      currentProductList: [],
      cartList: {}, // 按店铺 ID 存储购物车
      isCartPopupVisible: false,
      currentStoreId: null, // 当前店铺 ID
      activeTab: 'all' // 当前选中的标签
    };
  },
  onLoad(options) {
    this.currentStoreId = options.id;
    this.initData(this.currentStoreId);
  },
  onShow() {
    // 每次页面显示时重新加载购物车数据
    this.loadCartFromLocalStorage();
  },
  computed: {
    // 当前店铺的购物车
    currentStoreCart() {
      return this.cartList[this.currentStoreId] || [];
    },

    // 当前店铺购物车是否有商品
    hasItemsInCurrentStoreCart() {
      return this.currentStoreCart.length > 0;
    },

    // 当前店铺选中商品总价
    currentStoreSelectedTotalPrice() {
      const total = this.currentStoreCart
        .filter(item => item.selected)
        .reduce((acc, item) => acc + (item.quantity * item.price), 0);
      return total.toFixed(2);
    },

    // 当前店铺是否全选
    isCurrentStoreAllSelected: {
      get() {
        if (this.currentStoreCart.length === 0) return false;
        return this.currentStoreCart.every(item => item.selected);
      },
      set(value) {
        if (this.cartList[this.currentStoreId]) {
          this.cartList[this.currentStoreId].forEach(item => {
            item.selected = value;
          });
          this.saveCartListToLocalStorage();
        }
      }
    }
  },
  methods: {
    async initData(storeId) {
      try {
        await Promise.all([
          this.fetchStoreDetail(storeId),
          this.fetchAllProducts(storeId),
          this.fetchSeckillProducts(storeId),
          this.fetchFreshFruitProducts(storeId)
        ]);
        this.loadCartFromLocalStorage();
      } catch (error) {
        console.error('初始化数据出错:', error);
      }
    },

    // API 请求方法
    fetchStoreDetail(storeId) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.api_host}super`,
          data: { _id: storeId },
          success: (res) => {
            this.storeInfo = res.data[0];
            resolve();
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    fetchAllProducts(storeId) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.api_host}productsAll`,
          data: { storeId },
          success: (res) => {
            this.allProducts = res.data;
            this.currentProductList = [...this.allProducts];
            resolve();
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    fetchSeckillProducts(storeId) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.api_host}productsSeckill`,
          data: { storeId },
          success: (res) => {
            this.seckillProducts = res.data;
            resolve();
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    fetchFreshFruitProducts(storeId) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.api_host}productsFruit`,
          data: { storeId },
          success: (res) => {
            this.freshFruitProducts = res.data;
            resolve();
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 商品展示切换
    showAllProducts() {
      this.activeTab = 'all';
      this.currentProductList = [...this.allProducts];
    },

    showSeckillProducts() {
      this.activeTab = 'seckill';
      this.currentProductList = [...this.seckillProducts];
    },

    showFreshFruitProducts() {
      this.activeTab = 'fruit';
      this.currentProductList = [...this.freshFruitProducts];
    },

    // 获取商品在购物车中的数量
    getProductQuantity(product) {
      const storeCart = this.cartList[this.currentStoreId] || [];
      const item = storeCart.find(i => i._id === product._id);
      return item? item.quantity : 0;
    },

    // 购物车操作方法
 addToCart(product) {
   const storeId = product.storeId || this.currentStoreId;
   
   // 确保响应式
   if (!this.cartList[storeId]) {
     this.$set(this.cartList, storeId, []);
   }
   
   const existingIndex = this.cartList[storeId].findIndex(item => item._id === product._id);
   
   if (existingIndex >= 0) {
     // 使用 Vue.set 确保响应式
     this.$set(this.cartList[storeId], existingIndex, {
       ...this.cartList[storeId][existingIndex],
       quantity: this.cartList[storeId][existingIndex].quantity + 1
     });
   } else {
     // 使用 push 方法会自动触发响应式
     this.cartList[storeId].push({
       ...product,
       quantity: 1,
       selected: true
     });
   }
   
   this.saveCartListToLocalStorage();
   // 不再需要 forceUpdate
 },

    changeCartItemQuantity(item, step) {
      const storeCart = this.cartList[this.currentStoreId] || [];
      const productIndex = storeCart.findIndex(p => p._id === item._id);
    
      if (productIndex >= 0) {
        if (step === 1 || (step === -1 && storeCart[productIndex].quantity > 1)) {
          // 使用 Vue.set 确保响应式
          this.$set(this.cartList[this.currentStoreId], productIndex, {
            ...storeCart[productIndex],
            quantity: storeCart[productIndex].quantity + step
          });
        } else if (step === -1 && storeCart[productIndex].quantity === 1) {
          // 使用 splice 而不是 filter 确保响应式
          this.cartList[this.currentStoreId].splice(productIndex, 1);
        }
        this.saveCartListToLocalStorage();
      }
    },
  decreaseQuantity(product) {
    const storeCart = this.cartList[this.currentStoreId] || [];
    const existingIndex = storeCart.findIndex(item => item._id === product._id);
  
    if (existingIndex >= 0) {
      if (storeCart[existingIndex].quantity > 1) {
        // 使用 Vue.set 确保响应式
        this.$set(this.cartList[this.currentStoreId], existingIndex, {
          ...storeCart[existingIndex],
          quantity: storeCart[existingIndex].quantity - 1
        });
      } else {
        // 使用 splice 而不是 filter 确保响应式
        this.cartList[this.currentStoreId].splice(existingIndex, 1);
      }
      this.saveCartListToLocalStorage();
    }
  },
    // 购物车管理
    toggleCartPopup() {
      this.isCartPopupVisible = !this.isCartPopupVisible;
      // 每次打开弹窗时刷新数据
      if (this.isCartPopupVisible) {
        this.loadCartFromLocalStorage();
      }
    },

    // 清空当前店铺购物车
  clearCurrentStoreCart() {
    uni.showModal({
      title: '提示',
      content: '确定要清空购物车吗？',
      success: (res) => {
        if (res.confirm) {
          // 使用 Vue.set 确保响应式
          this.$set(this.cartList, this.currentStoreId, []);
          this.saveCartListToLocalStorage();
          this.isCartPopupVisible = false;
        }
      }
    });
  },

    // 获取当前店铺购物车商品总数
    getCurrentStoreCartQuantity() {
      const storeCart = this.cartList[this.currentStoreId] || [];
      return storeCart.reduce((acc, item) => acc + item.quantity, 0);
    },

    // 数据同步与存储
    saveCartListToLocalStorage() {
      const cartToSave = JSON.parse(JSON.stringify(this.cartList));
      try {
        wx.setStorageSync('cartList', cartToSave);
      } catch (e) {
        console.error('存储购物车数据失败:', e);
      }
    },

    loadCartFromLocalStorage() {
      try {
        const savedCart = wx.getStorageSync('cartList') || {};
        // 初始化每个店铺的购物车商品选中状态
        Object.keys(savedCart).forEach(storeId => {
          savedCart[storeId] = savedCart[storeId].map(item => ({
            ...item,
            selected: item.selected!== undefined? item.selected : true
          }));
        });
        this.cartList = savedCart;
        console.log('加载后的购物车数据:', this.cartList);
      } catch (error) {
        console.error('加载购物车数据失败:', error);
        this.cartList = {};
      }
    },

    // 选择功能
    toggleCurrentStoreAllSelection() {
      this.isCurrentStoreAllSelected = !this.isCurrentStoreAllSelected;
    },

    toggleProductSelection(item) {
      item.selected = !item.selected;
      this.saveCartListToLocalStorage();
      this.$forceUpdate();
    },

    // 结算当前店铺选中的商品
    checkout() {
      const selectedItems = this.currentStoreCart.filter(item => item.selected);
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }

      const cartListString = encodeURIComponent(JSON.stringify(selectedItems));
      uni.navigateTo({
        url: `/pages/address/Addlist?cartList=${cartListString}`
      });
    }
  }
};    
</script>
<style>
/* 样式保持不变，与之前相同 */
.store-detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.store-header {
  display: flex;
  padding: 15px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.store-logo image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
}

.store-basic-info {
  flex: 1;
  margin-left: 15px;
}

.store-name {
  font-size: 18px;
  font-weight: bold;
}

.store-meta {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  font-size: 12px;
  color: #666;
}

.store-slogan {
  font-size: 12px;
  color: #ff4444;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.button-column {
  width: 90px;
  background: #f5f5f5;
  overflow-y: auto;
}

.button-item {
  padding: 15px 10px;
  text-align: center;
  font-size: 14px;
  border-bottom: 1px solid #eee;
  color: #666;
  background-color: #f5f5f5;
  transition: all 0.2s ease;
}

/* 新增的选中状态样式 */
.button-item.active {
  color: #007AFF;
  font-weight: bold;
  background-color: #fff;
  border-left: 3px solid #007AFF;
}

/* 悬停效果 */
.button-item:hover {
  background-color: #e8f4ff;
}

.product-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.product-item {
  display: flex;
  margin-bottom: 15px;
  background: #fff;
  padding: 10px;
  border-radius: 8px;
}

.product-img image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
}

.product-sales {
  font-size: 12px;
  color: #666;
}

.product-price {
  display: flex;
  align-items: center;
}

.price-current {
  color: #ff4444;
  font-size: 16px;
  font-weight: bold;
}

.price-old {
  color: #999;
  font-size: 12px;
  text-decoration: line-through;
  margin-left: 5px;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.minus, .plus {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
}

.minus:active, .plus:active {
  transform: scale(0.9);
}

.quantity-num {
  margin: 0 10px;
}

.bottom-nav {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background: #fff;
  border-top: 1px solid #eee;
}

.cart-icon {
  position: relative;
  margin-right: 15px;
}

.cart-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4444;
  color: #fff;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cart-icon image {
  width: 30px;
  height: 30px;
}

.total-price {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
}

.checkout-btn {
  background: #ff4444;
  color: #fff;
  padding: 8px 20px;
  border-radius: 20px;
}

.cart-popup {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  background: #fff;
  max-height: 60vh;
  overflow-y: auto;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  padding-bottom: 60px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.clear-cart {
  color: #666;
  font-size: 14px;
}

.product-item-popup {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.product-select {
  margin-right: 10px;
}

.product-img-popup image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
}

.product-info-popup {
  flex: 1;
}

.product-name-popup {
  font-size: 16px;
  margin-bottom: 5px;
}

.product-sales-popup {
  font-size: 12px;
  color: #666;
  display: block;
  margin-bottom: 5px;
}

.product-price-popup {
  display: flex;
  align-items: center;
}

.price-current-popup {
  color: #ff4444;
  font-size: 16px;
  font-weight: bold;
}

.price-old-popup {
  color: #999;
  font-size: 12px;
  text-decoration: line-through;
  margin-left: 5px;
}

.quantity-control-popup {
  display: flex;
  align-items: center;
  margin-left: 15px;
}

.quantity-control-popup view {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
}

.quantity-control-popup view:active {
  transform: scale(0.9);
}

.quantity-control-popup .quantity-num {
  margin: 0 10px;
}
</style>